package DGWeb.Servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import com.google.gson.Gson;

import DGWeb.AppConstants;
import DGWeb.Model.model_MessageInsert;

/**
 * Servlet implementation class messageInsert
 */
@SuppressWarnings("deprecation")
@WebServlet("/messageInsert")
public class messageInsert extends HttpServlet implements SingleThreadModel {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public messageInsert() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		HttpSession UserSession = request.getSession();
		DateFormat dateFormat = new SimpleDateFormat(AppConstants.TimeFormat);
		Context context = null;
		BasicDataSource ds = null;
		Connection conn = null;
		Statement stmt = null;
		
		String user = (String) UserSession.getAttribute("Username");
		String nick = (String) UserSession.getAttribute("Nickname");
		InputStreamReader isr = new InputStreamReader(request.getInputStream());
		BufferedReader br = new BufferedReader(isr);
		StringBuilder jsonFileContent = new StringBuilder();
		//read line by line from file
		jsonFileContent.append( br.readLine());
		//Pasre data
		Gson gson = new Gson();
		model_MessageInsert CurrMsg = gson.fromJson(jsonFileContent.toString(),model_MessageInsert.class );
		// Get Data
		String Text = CurrMsg.getText();
		String Type = CurrMsg.getType();
		String MsgID = CurrMsg.getMsgID(); // only used in republish mode
		
		try {
			context = new InitialContext();
			ds = (BasicDataSource)context.lookup(AppConstants.DB_DATASOURCE);
    		conn = ds.getConnection();
    		//create Customers table
			stmt = conn.createStatement();
			
			if (Type.equals("1") ) // 1 is Message
			{
				Type = AppConstants.MESSAGE_TYPE_MESSAGE;
				MsgID = "0";
				
			}
			else if ( Type.equals("2"))// Republish of a message
			{
				Type = AppConstants.MESSAGE_TYPE_REPUBLISH;
				//Text = "RE: "+ Text;
				// this code handle the case we do a republish to a message that have topic or User and it enters the html code to the database.
				String execFindMessage = AppConstants.GET_MESSAGE.replaceAll("//", MsgID); // find the message 
				ResultSet res = stmt.executeQuery(execFindMessage);
				res.next();
				Text = res.getString(AppConstants.MESSAGES_TEXT);
				Text = "RE: "+ Text;
				
				res.close();
				
				
			}else if ( Type.equals("3")) // republish of a comment
			{
				Type = AppConstants.MESSAGE_TYPE_REPUBLISH_COMMENT;
				//Text = "RE: "+ Text;
				// this code handle the case we do a republish to a message that have topic or User and it enters the html code to the database.
				String execFindMessage = AppConstants.GET_COMMENT_SELECT_BY_ID.replaceAll("//", MsgID); // find the message 
				ResultSet res = stmt.executeQuery(execFindMessage);
				res.next();
				Text = res.getString(AppConstants.MESSAGES_TEXT);
				Text = "RE: "+ Text;
				
				res.close();
			}

		String t = AppConstants.MESSAGES_INSERT;
		String[] Dt = t.split("//");
		
		String exec = Dt[0] + user + Dt[1]+ Text + Dt[2] + dateFormat.format(Calendar.getInstance().getTime()) +Dt[3]+nick+Dt[4]+Type+Dt[5]+MsgID+Dt[6] ;
		 
		//for insert
		stmt.executeUpdate(exec);
		// Get Back the Message ID - because in the client side we push all the details locali and we need the msg id to activate the replies
		String execGetLastID = AppConstants.GET_MESSAGE_LAST; // find the message th
		ResultSet res = stmt.executeQuery(execGetLastID);
		// TBD
		res.next();
		
		String NewID = res.getString(AppConstants.MESSAGES_ID); // New Id of the Message
		UserSession.setAttribute(AppConstants.MESSAGES_ID, NewID); // set the new message to the http session
		// ADD TOPICS
		AddTopics(Text,NewID);
		//END OF ADDING TOPICS
		
		res.close();
		conn.commit();
		stmt.close();
		conn.close();
		context.close();
			
		} catch (NamingException |SQLException e) {

			try {
				if (stmt != null)
				stmt.close();
				if (context != null)
					context.close();
				if ( conn != null )
					conn.close();
				throw e;
			} catch (NamingException|SQLException e1) {
				
				e1.printStackTrace();
			}
		} 
		
	} // end of doPost
	
	public static void AddTopics(String Text,String MsgID) throws SQLException, NamingException
	{
		String[] dt = Text.split(" ");
		for ( int i= 0 ; i < dt.length ; i++)
		{
			if (dt[i].startsWith("#") )
			{
				Context context = null;
				BasicDataSource ds = null;
				Connection conn = null;
				Statement stmt = null;
				ResultSet res= null;
				try {
					context = new InitialContext();
					ds = (BasicDataSource)context.lookup(AppConstants.DB_DATASOURCE);
		    		conn = ds.getConnection();
		    		//create Customers table
					stmt = conn.createStatement();
					String exec = AppConstants.GET_TOPICS_BY_MSGID_AND_TEXT.replaceFirst("//", MsgID).replaceFirst("//", dt[i]);
					res = stmt.executeQuery(exec);
					if ( !res.next()) // if we dont have this Topic in the msg id - add it
					{
						 exec = AppConstants.TOPICS_INERT.replaceFirst("//", dt[i]).replaceFirst("//", MsgID);
						 stmt.executeUpdate(exec);
					}

					if (res != null)
						res.close();
					if (stmt != null)
						stmt.close();
					if (context != null)
						context.close();
					if ( conn != null )
						conn.close();
					
				}catch (NamingException |SQLException e) {
				
						if (res != null)
							res.close();
						if (stmt != null)
							stmt.close();
						if (context != null)
							context.close();
						if ( conn != null )
							conn.close();
				}
			}
		}
	}

}
